# coding:utf-8

import sys
import os
import commands
import shutil
import zipfile
import re

from sdk_tools import sdk_util

def try_rm(path):
    try:
        if os.path.exists(path):
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)
        else:
            print(path+' not exists');
    except Exception, e:
        pass

if __name__ == '__main__':
    apkfile   = sys.argv[1]
    server_paths = sys.argv[2]
    print(server_paths)
    agent_id = sys.argv[3]
    print(agent_id)
    cver = sys.argv[4]
    jver = sys.argv[5]
    signApk = ""
    predir = "pre_tmp"
    if len(sys.argv) > 6:
        signApk = sys.argv[6]
        if len(sys.argv) > 7:
            predir = sys.argv[7]
    pkgname_user = sys.argv[8]
    print("pkgname_user=",pkgname_user)
    t1_t2 = sys.argv[9]
    # 0.初始化
    SAVE_DIR = "./"
    #SAVE_DIR = "/datastorage/riskstub"
    CUR_DIR = os.path.dirname(os.path.realpath(__file__))
    print(CUR_DIR)
    TOOLS_DIR = CUR_DIR + '/sdk_tools/tools'
    PRE_TMPDIR = CUR_DIR + '/' + predir
    print(PRE_TMPDIR)
    TMPDIR    = PRE_TMPDIR + '/tmp'
    print(TMPDIR)
    SMALI_DIR = os.path.join(TMPDIR, "smali")
    print(SMALI_DIR)
    filedir,filename = os.path.split(apkfile)
    fname, ext = os.path.splitext(filename)
    unsignedApk    = "%s_unsigned%s" % (fname, ext)
    if len(signApk) == 0:
        signApk   = "%s/%s_%s_signed%s" % (SAVE_DIR, predir, fname, ext)
    print(signApk)

    try_rm(PRE_TMPDIR)
    os.mkdir(PRE_TMPDIR)
    TMP_APKFILE = PRE_TMPDIR + "/" + filename
    shutil.copyfile(apkfile,TMP_APKFILE)
    print(TMP_APKFILE)
    os.chdir(PRE_TMPDIR)
    # 1. 解包     
    cmd = "java  -jar " + TOOLS_DIR + "/apktool_2.0.1.jar d -f -o " + TMPDIR + ' ' + TMP_APKFILE
    print(">>CMD", cmd)
    os.system(cmd)
    # 2.2生成风控包dex
    os.system(TOOLS_DIR+ "/dex2jar/d2j-jar2dex.sh --force " + CUR_DIR + "/data/RiskStubLoader.jar")
    # 2.3解开风控包classes.dex到smali目录
    sdk_util.unzip_classes(os.path.join(PRE_TMPDIR, "RiskStubLoader-jar2dex.dex"), SMALI_DIR)
    # 同步sot等处理
    os.system("/bin/bash "+ CUR_DIR + "/call_deal.sh " + apkfile + " " + cver + " " + jver + " " + CUR_DIR + " " + TMPDIR)
    #3 在mainactivity里添加smali的代码
    main_activitys = sdk_util.getpackage_lanuch(TMPDIR + "/AndroidManifest.xml")
    if len(main_activitys) == 0:
        raise Exception('no MainActivity')
    else:
        print("main_activities="+main_activitys)
        for main_activity in main_activitys.split("||"):
            print("add coce", SMALI_DIR, main_activity)
            sdk_util.inject_smali(SMALI_DIR, main_activity)
    
    #修改服务器地址和agent id
    sdk_util.inject_12306_str_2_smali(SMALI_DIR + "/com/bangcle/everisk/shell/RiskStubShell.smali", agent_id)
    if server_paths != 'null':
        sdk_util.inject_ip_info_2_smali(SMALI_DIR + "/com/bangcle/everisk/shell/HostMgr.smali", server_paths, server_paths, "")
    else:
        sdk_util.inject_ip_info_2_smali(SMALI_DIR + "/com/bangcle/everisk/shell/HostMgr.smali", "http://123.59.84.160:7878", "http://101.201.211.46:7878", "http://route.everisker.com:7879/route/addr")
    #修改Loader的delay延时时间
    [delay1,delay2] = re.findall("\d+",t1_t2);
    print("t1=",delay1);
    print("t2=",delay2);
    sdk_util.inject_loader_delay_2_smali(SMALI_DIR + "/com/bangcle/everisk/shell/RiskStubShell.smali",delay1,delay2);

    #在这里调用一对一的脚本
    user_shell_file = CUR_DIR + "/user_shell/" + pkgname_user
    if os.path.exists(user_shell_file):
        cmd = user_shell_file + " " + PRE_TMPDIR
        print(">>CMD",cmd)
        os.system(cmd)
    else:
        print("user_shell_file not exists " + user_shell_file);

    # 4 重新打包apk
    cmd = "java  -jar " + TOOLS_DIR + "/apktool_2.0.1.jar b -f -o " + unsignedApk + ' ' + TMPDIR
    print(">>CMD", cmd)
    os.system(cmd)
    # 5 签名    
    os.chdir(CUR_DIR)
    cmd = "jarsigner -keystore " + TOOLS_DIR + "/com.appmagic.keystore -storepass 123456 -digestalg SHA1 -sigalg MD5withRSA -signedjar " + signApk + " " + PRE_TMPDIR + "/" + unsignedApk + " appmagic";
    print(cmd)
    commands.getstatusoutput(cmd )

    if not os.path.exists("/tmp/local_test_risk"):
        try_rm(PRE_TMPDIR)

